<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="queryParams.type" @change="handleQuery">
            <el-radio-button label="my">我的</el-radio-button>
            <el-radio-button label="region">区域</el-radio-button>
            <el-radio-button label="all">全部</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="familyName">
          <el-input
            v-model="queryParams.familyName"
            placeholder="名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['genealogy:society:add']"
          type="success"
          icon="plus"
          @click="handleOpenDialog()"
        >
          新增
        </el-button>
        <el-button
          v-hasPerm="['genealogy:society:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="宗亲会ID" prop="id" min-width="150" align="center" />
        <el-table-column
          key="familyName"
          label="宗亲会名称"
          prop="familyName"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="mergerName"
          label="行政区划"
          prop="mergerName"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="originPlace"
          label="宗亲会发源地"
          prop="originPlace"
          min-width="150"
          align="center"
        />
        <el-table-column key="totem" label="宗亲会图腾" prop="totem" min-width="150" align="center" />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updateTime"
          label="更新时间"
          prop="updateTime"
          min-width="150"
          align="center"
        />

        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-col>
            <el-button
              v-hasPerm="['genealogy:society:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            </el-col>
            <el-col>
            <el-button
              :type="
                scope.row.joinStatus === 1 ? 'success' : 
                scope.row.joinStatus === 0 ? 'warning' : 
                scope.row.joinStatus === 2 ? 'danger' : 'primary'
              "
              size="small"
              link
              @click="joinSociety(scope.row.id)"
            >
              <template #icon>
                <Edit />
              </template>
                {{ 
                  scope.row.joinStatus === 1 ? "查看宗亲会" : 
                  scope.row.joinStatus === 0 ? "审核中" : 
                  scope.row.joinStatus === 2 ? "被拒绝" : "加入宗亲会" 
                }}
            </el-button>
            </el-col>
            <el-col>
            <el-button
              v-hasPerm="['genealogy:society:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
            </el-col>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 宗亲会信息表单弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      :size="drawerSize"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="宗亲会名称" prop="familyName">
          <el-input v-model="formData.familyName" placeholder="宗亲会名称" />
        </el-form-item>

        <el-form-item label="宗亲会发源地" prop="originPlace">
          <el-input v-model="formData.originPlace" placeholder="宗亲会发源地" />
        </el-form-item>
        <el-form-item label="行政区划" prop="areaCode">
          <el-tree-select
            v-model="formData.areaCode"
            placeholder="选择行政区划"
            :data="regionOptions"
            filterable
            check-strictly
            :render-after-expand="false"
            :props="{
              isLeaf: (data) => data.level === 5,
              label: 'name',
              value: 'areaCode',
              children: 'children',
              level: 'level'
            }"
            :load="loadRegionNodes"
            lazy
            @change="handSelectLevel"
          />
        </el-form-item>

        <el-form-item label="宗亲会图腾" prop="totem">
          <el-input v-model="formData.totem" placeholder="宗亲会图腾" />
        </el-form-item>

        <el-form-item label="加入码" prop="joinCode">
          <el-input v-model="formData.joinCode" placeholder="加入码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import FamilyAPI from "@/api/genealogy/family.api";
import { ElMessage,ElMessageBox } from "element-plus";
import { DeviceEnum } from "@/enums/index.js";
import { useAppStore,useUserStore,usePermissionStore } from "@/store";
import router from "@/router";
import RegionAPI from "@/api/system/region.api.js";
import AuthAPI from "@/api/auth.api";
import { getAccessToken,setRefreshToken,setAccessToken } from "@/utils/auth";
const appStore = useAppStore();
const userStore = useUserStore();
const PermissionStore = usePermissionStore();

defineOptions({
  name: "Family",
  inheritAttrs: false,
});
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));
const queryFormRef = ref();
const dataFormRef = ref();
const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
// 顶级行政区划下拉选项
const regionOptions = ref([]);
const queryParams = reactive({
  familyName: "",
  pageNum: 1,
  pageSize: 10,
  type: "my", // 默认查询全部
});

// 宗亲会信息表格数据
const pageData = ref([]);

// 弹窗
const dialog = reactive({
  title: "新增宗亲会",
  visible: false,
});

// 初始行政区划表单数据
const initialFormData = ref({
  id: undefined,
  familyName: "",
  originPlace: "",
  totem: "",
});
// 宗亲会信息表单数据
const formData = ref({ ...initialFormData.value });

// 宗亲会信息表单校验规则
const rules = reactive({
  familyName: [{ required: true, message: "请输入宗亲会名称", trigger: "blur" }],
  originPlace: [{ required: true, message: "请输入发源地", trigger: "blur" }],
  areaCode: [{ required: true, message: "请输入行政区划", trigger: "blur" }],
  totem: [{ required: true, message: "请输入图腾/象征", trigger: "blur" }],
});

// 存储树选择组件的节点数据
const treeNodeMap = ref(new Map());

/** 查询宗亲会信息 */
function handleQuery() {
  loading.value = true;
  
  let queryMethod;
  switch(queryParams.type) {
    case 'region':
      queryMethod = FamilyAPI.getRegionPage;
      break;
    case 'my':
      queryMethod = FamilyAPI.getMyPage;
      break;
    case 'all':
    default:
      queryMethod = FamilyAPI.getPage;
      break;
  }
  
  queryMethod(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 加入宗亲会信息 */
function joinSociety(societyId) {
  const currentSociety = pageData.value.find((item) => item.id === societyId);
  if (currentSociety) {
    if (currentSociety.joinStatus === 1) {
      // 如果已加入，则查看宗亲会
      router.push({ name: "ViewSociety", params: { societyId: societyId } });
    } else if (currentSociety.joinStatus === 0) {
      ElMessage.info("您的加入申请正在审核中，请耐心等待");
    } else if (currentSociety.joinStatus === 2) {
      ElMessageBox.alert(
        `您的申请被拒绝，拒绝理由请查阅通知`,
        "申请被拒绝",
        {
          confirmButtonText: "重新申请",
          type: "error",
          callback: (action) => {
            if (action === "confirm") {
              // 跳转到宗亲会申请表
              router.push({ name: "Application", params: { societyId: societyId } });
            }
          }
        }
      );
    } else {
      // 未加入(null状态)，直接跳转到宗亲会申请表
      router.push({ name: "Application", params: { societyId: societyId } });
    }
  }
}

/** 重置宗亲会信息查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection) {
  removeIds.value = selection.map((item) => item.id);
}

/** 打开宗亲会信息弹窗 */
function handleOpenDialog(id) {
  // 初始化只加载省级数据
  RegionAPI.getOptions({ type: 0, areaCode: 0 })
    .then((data) => {
      regionOptions.value = data;
      // 存储初始节点数据
      data.forEach(item => {
        treeNodeMap.value.set(item.areaCode, item);
      });
    })
    .then(() => {
      dialog.visible = true;
      if (id) {
        dialog.title = "修改宗亲会信息";
        FamilyAPI.getFormData(id).then((data) => {
          Object.assign(formData.value, data);
        });
      } else {
        dialog.title = "新增宗亲会信息";
      }
    });
}

/** 提交宗亲会信息表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      const id = formData.value.id;
      if (id) {
        FamilyAPI.update(id, formData.value)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        FamilyAPI.create(formData.value)
          .then(() => {
            AuthAPI.refreshToken(getAccessToken()).then((data) => {
              setAccessToken(data.accessToken);
              setRefreshToken(data.refreshToken);
              useUserStore().userInfo = userStore.getUserInfo();
              // 重新加载路由以反映权限变化
              PermissionStore.resetRouter();
              PermissionStore.generateRoutes().then((dynamicRoutes) => {
                dynamicRoutes.forEach((route) => router.addRoute(route));
              });
              handleResetQuery();
            });
            ElMessage.success("新增成功");
            handleCloseDialog();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭宗亲会信息弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除宗亲会信息 */
function handleDelete(id) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      FamilyAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 懒加载行政区划节点
function loadRegionNodes(node, resolve) {
  if (node.level === 0) {
    // 根节点，已在初始化时加载省级数据
    return resolve(regionOptions.value);
  }
  
  // 根据当前节点级别确定请求的type值
  const type = node.level;
  // 使用当前节点的areaCode作为请求参数
  const areaCode = node.data.areaCode;
  
  RegionAPI.getOptions({ type, areaCode })
    .then(data => {
      // 返回子节点数据
      // 存储所有加载的节点数据，用于后续查询
      data.forEach(item => {
        treeNodeMap.value.set(item.areaCode, item);
      });
      resolve(data);
    })
    .catch(() => {
      resolve([]);
    });
}

function handSelectLevel(data) {
  if (!data) return;
  
  // 直接从映射中获取节点数据
  const selectedNode = treeNodeMap.value.get(data);
  console.log('选中节点:', selectedNode);
  
  if (selectedNode) {
    if (selectedNode.level && selectedNode.level === 5) {
      // 选择的是村或居委会级别，有效
      console.log('选中有效节点:', selectedNode.name);
    } else {
      formData.value.areaCode = null;
      ElMessage.error("请选择到村或居委会");
    }
  } else {
    console.error('未能找到选中节点信息:', data);
  }
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.el-form-item-tip {
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.member-info-template {
  margin-top: 10px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;
}

.template-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #606266;
}

.template-content {
  color: #909399;
  line-height: 1.5;
  margin: 0;
}
</style>
